//
//  BBAppController.m
//  BBTUIOTest
//
//  Created by ben smith on 7/18/08.
//  This file is part of BBTUIOTest.
//
//  BBTUIOTest is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  BBTUIOTest is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.

//  You should have received a copy of the GNU Lesser General Public License
//  along with BBTUIOTest.  If not, see <http://www.gnu.org/licenses/>.
// 
//  Copyright 2008 Ben Britten Smith ben@benbritten.com .
//
//
//

#import "BBAppController.h"

#import "BBTestAppView.h"
#import "BBDispatchViewDelegate.h"

@implementation BBAppController

@synthesize oscListener;
@synthesize portNumber;

-(void)awakeFromNib
{
	[NSApp setDelegate:self];
	[self disconnect];
	
	// make a nice default number
	self.portNumber = 3333;
}


// make a dispatch delegate and point it at the view
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
	dispatchViewDelegate = [[BBDispatchViewDelegate alloc] init];
	[dispatchViewDelegate setMainView:mainView];
	[dispatchViewDelegate setMouseFaker:mouseFaker];
	// connect to the sender
}

// this turns the port listener on and off
-(IBAction)toggleConnection:(id)sender
{
	if (self.oscListener == nil) {
		[self connect]; // then connect
		return;		
	} 
	[self disconnect];
}

-(void)connect
{
	// make a new listener, point it at the specified port
	// and hook it up to the dispatch delegate
	BBOSCListener * newListener = [[BBOSCListener alloc] init];
	[newListener setDelegate:dispatchViewDelegate];
	[newListener startListeningOnPort:portNumber];

	// keep a copy for myself
	self.oscListener = newListener;

	// clean up
	[newListener release];

	// UI update
	[connectionButton setTitle:@"Stop Listening"];
}

-(void)disconnect
{
	// this will release the old oscListener which will 'clean up' the port
	self.oscListener = nil;
	// update ui
	[connectionButton setTitle:@"Start Listening"];
}

-(IBAction)browseForImageDirectory:(id)sender
{
	int result;
	NSOpenPanel *oPanel = [NSOpenPanel openPanel];
	
	[oPanel setAllowsMultipleSelection:NO];
	[oPanel setCanChooseFiles:NO];
	[oPanel setCanChooseDirectories:YES];
	result = [oPanel runModalForDirectory:NSHomeDirectory()
																	 file:nil types:nil];
	NSString * key = @"BBPhotoDirectory";
	if (result == NSOKButton) {
		NSArray *filesToOpen = [oPanel filenames];
		NSString *aFile = [filesToOpen objectAtIndex:0];
		[[NSUserDefaults standardUserDefaults] setObject:aFile forKey:key];
	}
}

@end


